<template>
  <div>
    <div class="goods">
      <goodsitem
        v-for="item in goodslist"
        id="goodslist"
        :key="item.id"
        :url="item.img_url"
        :describe="item.title"
        @click.native="$router.push(`/particulars/${item.id}`)"
      >
        <template #default>
          <div class="price">
            <span class="new-price">￥{{ item.sell_price }}</span
            ><span class="old-price">￥{{ item.market_price }}</span>
          </div>
          <div class="text">
            <span>热卖中</span><span>剩余{{ item.stock_quantity }}件</span>
          </div>
        </template>
      </goodsitem>
    </div>
    <van-divider v-if="isLoadDone">已经全部加载</van-divider>
  </div>
</template>

<script>
import _ from "lodash";
import goodsitem from "@/component/GoodsItem.vue";
import { reqGetPagGoods } from "@/api";
export default {
  components: {
    goodsitem,
  },
  data() {
    return {
      goodslist: [],
      page: 1,
      pagesize: 10,
      isLoadDone: false,
    };
  },
  methods: {
    async getGoodsList() {
      let { message } = await reqGetPagGoods(this.page, this.pagesize);
      this.goodslist = message;
    },
    async loadGoodsList() {
      if (this.isLoadDone) {
        return;
      }
      //滚上去的高度
      let scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
      //   网页视口的宽度
      let windowHeight = document.documentElement.clientHeight || document.body.clientHeight;
      //整个页面的高度
      let pageHeight = document.documentElement.scrollHeight || document.body.scrollHeight;
      if (Math.ceil(scrollTop) + windowHeight === pageHeight) {
        this.page++;
        let { message } = await reqGetPagGoods(this.page, this.pagesize);
        if (message.length === 0) {
          this.isLoadDone = true;
          return;
        }
        this.goodslist = [...this.goodslist, ...message];
      }
    },
  },
  created() {
    this.throttleLoadGoodsList = _.throttle(this.loadGoodsList, 300);
  },
  mounted() {
    this.getGoodsList();
    document.addEventListener("scroll", this.throttleLoadGoodsList);
  },
  beforeUnmount() {
    document.removeEventListener("scroll", this.throttleLoadGoodsList);
  },
};
</script>

<style lang="scss" scoped>
.goods {
  display: flex;
  flex-wrap: wrap;
  padding: 5px;
  margin-bottom: 50px;

  #goodslist {
    margin: 5px;
  }

  .price {
    .new-price {
      margin-right: 10px;
      font-size: 16px;
      color: orange;
    }

    .old-price {
      font-size: 12px;
      text-decoration: line-through;
    }
  }

  .text {
    display: flex;
    justify-content: space-between;
    font-size: 14px;
  }
}

.van-divider {
  border-color: #c3c5c8;
}
</style>
